package com.yan.config;

import com.yan.pojo.User;
import com.yan.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author ：Yan Guang
 * @date ：Created in 2020/11/18 14:37
 * @description：
 */
//自定义的shiro
public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;

    //授权
    @Override//同样的，每次经过授权都会经过次方法，我们可以把我们的数据放在这里接受授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //拿到当前登陆的这个对象
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();

        //将我们获取到的权限进行权限判断
        String gender = userService.find(user.getUsername());
        info.addStringPermission(gender);

        System.out.println("执行了授权doGetAuthorizationInfo");
        return info;
    }
    //认证
    @Override//每次认证的时候都会执行这个方法
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了认证doGetAuthenticationInfo");

        UsernamePasswordToken userToken=(UsernamePasswordToken)token;//这个token是全局性的，都可以调用
        //连接数据库
        User user = userService.getByName(userToken.getUsername());
        if (user==null){
            return null;//UnknownAccountException
        }

        /*也可以通过这种方式把user存在session里面，这样可以用thymeleaf里面去获取从而进行判断
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("loginUser",user);*/

        //密码认证，他自己做,密码也经过加密了,第一个值可以把我们的user对象给传给授权方法里面去
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
